﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;

namespace Commons
{
    /// <summary>
    /// LINQ比较器
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class FastPropertyComparer<T> : IEqualityComparer<T>
    {
        private readonly Func<T, Object> getPropertyValueFunc;

        /// <summary>
        /// 通过propertyName 获取PropertyInfo对象
        /// </summary>
        /// <param name="propertyName"></param>
        public FastPropertyComparer(string propertyName)
        {
            var _PropertyInfo = typeof (T).GetProperty(propertyName,
                                                       BindingFlags.GetProperty | BindingFlags.Instance |
                                                       BindingFlags.Public);
            if (_PropertyInfo == null)
            {
                throw new ArgumentException(string.Format("{0} is not a property of type {1}.",
                                                          propertyName, typeof (T)));
            }

            var expPara = Expression.Parameter(typeof (T), "obj");
            var me = Expression.Property(expPara, _PropertyInfo);
            getPropertyValueFunc = Expression.Lambda<Func<T, object>>(me, expPara).Compile();
        }

        #region IEqualityComparer<T> Members

        public bool Equals(T x, T y)
        {
            var xValue = getPropertyValueFunc(x);
            var yValue = getPropertyValueFunc(y);

            if (xValue == null)
                return yValue == null;

            return xValue.Equals(yValue);
        }

        public int GetHashCode(T obj)
        {
            var propertyValue = getPropertyValueFunc(obj);

            if (propertyValue == null)
                return 0;
            else
                return propertyValue.GetHashCode();
        }

        #endregion
    }
}